package com.example.ibsp_demo.service.impl;

import com.example.ibsp_demo.mapper.message.*;
import com.example.ibsp_demo.pojo.dto.message.PrivateMessageRequest;
import com.example.ibsp_demo.pojo.entity.message.*;
import com.example.ibsp_demo.pojo.entity.user.NotificationSetting;
import com.example.ibsp_demo.pojo.entity.user.User;
import com.example.ibsp_demo.pojo.response.ResponseMessage;
import com.example.ibsp_demo.service.impl.MessageService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MessageService {

    @Autowired
    private LikeMessageMapper likeMessageMapper;

    @Autowired
    private CommentMessageMapper commentMessageMapper;

    @Autowired
    private PrivateSessionMapper privateSessionMapper;

    @Autowired
    private PrivateMessageMapper privateMessageMapper;

    @Autowired
    private FollowNotificationMapper followNotificationMapper;

    @Autowired
    private MSNotificationSettingMapper notificationSettingMapper;

    @Autowired
    private ActivityNotificationMapper activityNotificationMapper;

    // 1. 获取点赞消息列表
    public List<LikeMessage> getLikeMessages(int userId) {
        List<LikeMessage> likes =  likeMessageMapper.selectLikeMessageByUid(userId);
        return likes;
    }

    // 2. 获取评论消息列表
    public List<CommentMessage> getCommentMessages(int userId) {
        return commentMessageMapper.selectCommentsByUid(userId);
    }

    // 3. 获取私信会话列表
    public List<PrivateSession> getPrivateSessions(int userId) {
        return privateSessionMapper.selectByUserId(userId);
    }

    // 4. 获取私信详情
    public List<PrivateMessage> getPrivateMessages(int sessionId, int page, int size) {
        int offset = (page - 1) * size;
        return privateMessageMapper.selectBySessionId(sessionId, offset, size);
    }

    // 获取某个会话的所有私信
    public List<PrivateMessage> getPrivateMessagesBySessionId(int sessionId, int page, int size) {
        int offset = (page - 1) * size;
        return privateMessageMapper.selectBySessionId(sessionId, offset, size);
    }

    public List<PrivateMessage> getAllMessagesBetweenUsers(int user1Id, int user2Id) {
        return privateMessageMapper.selectBySenderIdAndReceiverId(user1Id, user2Id);
    }

    // 5. 发送私信
    public boolean isUserInSession(int sessionId, int userId) {
        System.out.println("【MessageService.isUserInSession】尝试获取会话: " + sessionId);
        PrivateSession session = privateSessionMapper.selectById(sessionId);
        if (session == null) {
            System.out.println("【MessageService.isUserInSession】找不到会话 ID: " + sessionId);
            return false;
        }
        boolean result = session.getUser1Id() == userId || session.getUser2Id() == userId;
        System.out.println("【MessageService.isUserInSession】用户是否在会话中: " + result);
        return result;
    }

    public boolean sessionExists(int user1Id, int user2Id) {
        Map<String, Integer> userPair = new HashMap<>();
        userPair.put("user1Id", Math.min(user1Id, user2Id));
        userPair.put("user2Id", Math.max(user1Id, user2Id));
        return privateSessionMapper.selectByUserPair(userPair) != null;
    }

    public boolean isSessionExists(int user1Id, int user2Id) {
        Map<String, Integer> userPair = new HashMap<>();
        userPair.put("user1Id", Math.min(user1Id, user2Id));
        userPair.put("user2Id", Math.max(user1Id, user2Id));

        PrivateSession session = privateSessionMapper.selectByUserPair(userPair);
        return session != null;
    }



    @Transactional
    public boolean sendPrivateMessage(int senderId, int receiverId, String content) {
        System.out.println("【MessageService.sendPrivateMessage】发送私信，senderId=" + senderId + ", receiverId=" + receiverId + ", content=" + content);

        int user1Id = Math.min(senderId, receiverId);
        int user2Id = Math.max(senderId, receiverId);

        Map<String, Integer> userPair = new HashMap<>();
        userPair.put("user1Id", user1Id);
        userPair.put("user2Id", user2Id);

        PrivateSession session = privateSessionMapper.selectByUserPair(userPair);

        // 修复点：确保会话存在且正确处理
        if (session == null) {
            session = new PrivateSession();
            session.setUser1Id(user1Id);
            session.setUser2Id(user2Id);
            session.setCreateTime(LocalDateTime.now());
            privateSessionMapper.insert(session);
            System.out.println("【MessageService.sendPrivateMessage】创建新会话，ID: " + session.getSessionId());
        } else {
            System.out.println("【MessageService.sendPrivateMessage】使用现有会话，ID: " + session.getSessionId());
        }

        PrivateMessage message = new PrivateMessage();
        message.setSenderId(senderId);
        message.setReceiverId(receiverId);
        message.setContent(content);
        message.setSessionId(session.getSessionId());

        System.out.println("【MessageService.sendPrivateMessage】准备插入私信，session_id=" + session.getSessionId());
        try {
            privateMessageMapper.insert(message);
            System.out.println("【MessageService.sendPrivateMessage】私信插入成功，messageId=" + message.getMessageId());
        } catch (Exception e) {
            System.err.println("【MessageService.sendPrivateMessage】插入私信失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }

        session.setLastMessage(content);
        session.setLastMessageTime(LocalDateTime.now());
        privateSessionMapper.updateLastMessage(session);

        return true;
    }



    // 所有私信设置为已读
    public void markAllReadBySessionId(int sessionId, int userId) {
        privateMessageMapper.markAllReadBySessionId(sessionId, userId);
    }

    // 6. 删除私信
    public boolean deletePrivateMessage(int messageId) {
        return privateMessageMapper.deleteByMsgId(messageId) > 0;
    }

    public boolean deletePrivateSession(int sessionId) {
        // 1. 删除所有私信消息
        privateMessageMapper.deleteBySessionId(sessionId);
        // 2. 删除会话
        return privateSessionMapper.deleteSessionById(sessionId) > 0;
    }

    // 7. 获取关注提醒列表
    public List<FollowNotification> getFollowNotifications(int userId) {
        return followNotificationMapper.selectByUserId(userId);
    }

    // 8. 执行回关操作
    @Transactional
    public boolean followBack(int followerId, int followedId) {
        FollowNotification followNotification = new FollowNotification();
        followNotification.setFollowedId(followedId);
        followNotification.setFollowerId(followerId);
        followNotification.setFollowTime(LocalDateTime.now());
        followNotification.setRead(true);
        followNotificationMapper.insert(followNotification);
        return true;
    }

    // 9. 获取通知设置
    public NotificationSetting getNotificationSettings(int userId) {
        return notificationSettingMapper.selectByUserId(userId);
    }

    // 10. 更新通知设置
    public boolean updateNotificationSettings(NotificationSetting setting) {
        if (setting.getUid() == 0) {
            notificationSettingMapper.insert(setting);
        } else {
            notificationSettingMapper.update(setting);
        }
        return true;
    }

    // 11. 获取活动通知
    public List<ActivityNotification> getActivityNotifications(int userId) {
        return activityNotificationMapper.selectActivitys(userId);
    }

    // 标记会话为已读
    public void markSessionAsRead(int sessionId, int userId) {
        privateSessionMapper.markSessionAsRead(sessionId, userId);
    }
}
